# -*- coding: utf-8 -*-
# created on 2017/3/1

from mathsolver.functions.base import *
from sympy import Tuple
from sympy.abc import m, n


# 输出BaseSymbolValue
class EXSBaseSymbolValue(BaseFunction):
    def solver(self, *args):
        variable = args[0].sympify()
        value = args[1].sympify()
        self.output.append(BaseSymbolValue({variable: value}))
        return self


def exs_search_multiple(known, poly):
    symbols = poly.free_symbols
    answer = []
    for name in known:
        if isinstance(name, Tuple):
            new_name = set(name)
            if new_name & symbols <= new_name:
                values = known[name]
                for value in values:
                    value = list(value)
                    for sym, v in zip(name, value):
                        v_index = value.index(v)
                        if isinstance(v, Interval):
                            value[v_index] = sym
                    symbol_value = dict([(sym, v) for sym, v in zip(name, value)])
                    answer.append(symbol_value)
        else:
            if name in symbols:
                values = known[name]
                for value in values:
                    symbol_value = {name: value}
                    answer.append(symbol_value)
    return answer


def get_mul_coeff(poly):
    coeff = S.One
    if poly.is_Mul:
        for arg in poly.args:
            symbols = arg.free_symbols
            if not symbols:
                coeff *= arg
            else:
                if symbols <= {m, n}:
                    coeff *= arg
    return coeff


class EXSPolysEqual(BaseFunction):
    def solver(self, *args):
        new_poly1 = args[0].sympify()
        new_poly2 = args[1].sympify()
        expr = new_poly1 - new_poly2
        eq = [new_poly1, new_poly2]
        eqs = [eq]
        symbols = expr.free_symbols
        if n in symbols:
            eqs.append([n, ">", S.Zero])
        if str(expr).find("binomial") >= 0:
            answer = {}
            if "Eequations" in self.known:
                eeqs = self.search("Eequations")
            else:
                eeqs = []
            eeqs.extend(eqs)
            answer["Eequations"] = eeqs
            self.output.append(BaseErXiangShiValue(answer))
        else:
            self.output.append(BaseIneqs(eqs))
        self.steps.append(["", "由题意,得%s" % (BaseIneqs(eqs).printing())])
        return self
